/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var searchRange = function (nums, target) {
    let ans = [-1, -1];
    // leftIdnex即为寻找第一个大于等于target的下标 rightIndex即为寻找第一个大于target的下标故而需-1
    let leftIndex = search(nums, target, true);
    let rightIndex = search(nums, target, false) - 1;
    // 最后验证左右下标 不能超出长度 值是否正确
    if (leftIndex <= rightIndex && rightIndex <= nums.length && nums[leftIndex] === target && nums[rightIndex] === target) {
        ans = [leftIndex, rightIndex]
    }
    return ans;
};
/**
 * 
 * @param {number[]} nums 
 * @param {number} target 
 * @param {boolean} lower 
 */
const search = (nums, target, lower) => {
    let l = 0, r = nums.length - 1, ans = nums.length;
    while (l <= r) {
        const mid = Math.floor((l + r) / 2);
        // 当中间值大于目标值 目标在左半区 右指针左移
        // 当左值为真需要判断右值 当lower为true时 寻找的为第一个大于等于target的下标
        if (nums[mid] > target || (lower && nums[mid] >= target)) {
            r = mid - 1;
            ans = mid;
        } else {
            l = mid + 1;
        }
    }
    return ans;
}

module.exports = searchRange;